# python_basic.py

from typing import List, Dict, Generator, Optional
import contextlib


# ----------------------------
# 1. 基本与复杂数据结构示例
# ----------------------------

# 基本数据类型
name: str = "Alice"
age: int = 30
is_active: bool = True

# 基本数据结构
fruits: List[str] = ["apple", "banana", "cherry"]
coordinates: tuple = (10.0, 20.5)
unique_tags: set = {"python", "coding", "demo"}
person: dict = {"name": "Bob", "age": 25}

# 复杂数据结构：嵌套字典 + 列表推导式
employees: List[Dict] = [
    {"name": "Alice", "dept": "Engineering", "salary": 70000},
    {"name": "Bob", "dept": "HR", "salary": 50000},
    {"name": "Charlie", "dept": "Engineering", "salary": 80000},
]

# 使用列表推导式筛选高薪员工
high_earners: List[str] = [e["name"] for e in employees if e["salary"] > 60000]


# ----------------------------
# 2. 函数定义（含高级特性）
# ----------------------------

def greet(name: str, greeting: str = "Hello") -> str:
    """简单函数，带默认参数和返回值"""
    return f"{greeting}, {name}!"


def multiply(*args: int) -> int:
    """可变位置参数"""
    result = 1
    for x in args:
        result *= x
    return result


def create_profile(**kwargs) -> dict:
    """可变关键字参数"""
    return {"profile": kwargs}


# 装饰器：记录函数执行时间
def timer(func):
    def wrapper(*args, **kwargs):
        import time
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行耗时: {end - start:.4f} 秒")
        return result
    return wrapper


@timer
def slow_function():
    import time
    time.sleep(0.1)
    return "Done"


# 生成器函数：无限斐波那契数列
def fibonacci() -> Generator[int, None, None]:
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


# ----------------------------
# 3. 类定义（含高级特性）
# ----------------------------

class BankAccount:
    def __init__(self, owner: str, balance: float = 0.0):
        self.owner = owner
        self._balance = balance  # 受保护属性

    @property
    def balance(self) -> float:
        """使用 property 访问余额"""
        return self._balance

    def deposit(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("存款金额必须大于0")
        self._balance += amount

    def withdraw(self, amount: float) -> None:
        if amount > self._balance:
            raise ValueError("余额不足")
        self._balance -= amount

    def __str__(self) -> str:
        return f"账户: {self.owner}, 余额: {self._balance}"

    def __repr__(self) -> str:
        return f"BankAccount(owner='{self.owner}', balance={self._balance})"

    def __eq__(self, other) -> bool:
        if not isinstance(other, BankAccount):
            return False
        return self.owner == other.owner and self._balance == other._balance


# 上下文管理器示例
@contextlib.contextmanager
def managed_file(filename: str, mode: str = 'w'):
    try:
        f = open(filename, mode)
        yield f
    except Exception as e:
        print(f"文件操作出错: {e}")
        raise
    finally:
        f.close()


# ----------------------------
# 4. 异常处理示例
# ----------------------------

def risky_division(a: float, b: float) -> Optional[float]:
    try:
        return a / b
    except ZeroDivisionError:
        print("错误：不能除以零！")
        return None
    except TypeError as e:
        print(f"类型错误: {e}")
        return None